import json
from jsonpath_ng import parse

class InterfaceParser:
    def __init__(self, interface_file):
        with open(interface_file, 'r', encoding='utf-8') as f:
            self.interfaces = json.load(f)
        self.jsonpath_cache = {}

    def generate_request_example(self, method, url):
        for interface in self.interfaces:
            if interface['method'] == method and interface['url'] == url:
                return interface.get('request_body', {})
        return {}

    def generate_response_example(self, method, url):
        for interface in self.interfaces:
            if interface['method'] == method and interface['url'] == url:
                return interface.get('response_body', {})
        return {}

    def fill_request_body(self, method, url, values):
        request_body = self.generate_request_example(method, url)
        for value in values:
            field_name, field_value = value
            jsonpath = self._get_jsonpath(field_name)
            if jsonpath:
                jsonpath.update(request_body, field_value)
        return request_body

    def extract_response_value(self, response_body, field_names):
        result = {}
        for field_name in field_names:
            jsonpath = self._get_jsonpath(field_name)
            if jsonpath:
                match = jsonpath.find(response_body)
                if match:
                    result[field_name] = match[0].value
        return result

    def _get_jsonpath(self, field_name):
        if field_name not in self.jsonpath_cache:
            for interface in self.interfaces:
                for child in interface.get('request_body', {}).get('children', []):
                    if child['name'] == field_name:
                        self.jsonpath_cache[field_name] = parse(child['jsonpath'])
                        break
                for child in interface.get('response_body', {}).get('children', []):
                    if child['name'] == field_name:
                        self.jsonpath_cache[field_name] = parse(child['jsonpath'])
                        break
        return self.jsonpath_cache.get(field_name)

if __name__ == "__main__":
    parser = InterfaceParser('demo/interfaces_define.json')

    # 生成请求示例
    request_example = parser.generate_request_example("POST", "/links")
    print("Request Example:", json.dumps(request_example, ensure_ascii=False, indent=4))

    # 生成响应示例
    response_example = parser.generate_response_example("POST", "/links")
    print("Response Example:", json.dumps(response_example, ensure_ascii=False, indent=4))

    # 填充请求体
    values = [("链路ID", "12345"), ("链路名称", "测试链路"), ("链路级别，包括[铁级，银级，钻石级]", "钻石级"), ("有无保护，有保护为1，无保护为0", 1)]
    filled_request_body = parser.fill_request_body("POST", "/links", values)
    print("Filled Request Body:", json.dumps(filled_request_body, ensure_ascii=False, indent=4))

    # 从响应体中提取值
    response_body = {
        "linkId": "12345",
        "linkName": "测试链路",
        "level": "钻石级",
        "protected": 1,
        "endpoints": []
    }
    field_names = ["链路ID", "链路名称", "链路级别，包括[铁级，银级，钻石级]", "有无保护，有保护为1，无保护为0"]
    extracted_values = parser.extract_response_value(response_body, field_names)
    print("Extracted Values:", json.dumps(extracted_values, ensure_ascii=False, indent=4))
